package com.hanhai.zrb.backend.web.controller;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;





























import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hanhai.common.annotation.PermissionNeed;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IndustryService;
import com.hanhai.zrb.api.biz.service.IntentionService;
import com.hanhai.zrb.api.biz.service.ProjectFundSequenceService;
import com.hanhai.zrb.api.biz.service.ProjectService;
import com.hanhai.zrb.api.biz.service.ResourceMatchService;
import com.hanhai.zrb.api.biz.service.SequenceService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.api.client.facade.FundFacade;
import com.hanhai.zrb.backend.admin.dao.mybatis.BackUserRoleDao;
import com.hanhai.zrb.backend.admin.model.BackUser;
import com.hanhai.zrb.backend.admin.model.BackendUser;
import com.hanhai.zrb.backend.admin.service.BackUserService;
import com.hanhai.zrb.backend.admin.service.UserRoleService;
import com.hanhai.zrb.backend.util.BackendLoginUtil;
import com.hanhai.zrb.model.common.Sequence;
import com.hanhai.zrb.model.fund.Fund;
import com.hanhai.zrb.model.fund.dto.FundSearchDto;
import com.hanhai.zrb.model.fund.vo.AppFundDetailVo;
import com.hanhai.zrb.model.fund.vo.FundSearchVo;
import com.hanhai.zrb.model.intention.Intention;
import com.hanhai.zrb.model.intention.enums.IntentionTypeEnum;
import com.hanhai.zrb.model.photo.Photo;
import com.hanhai.zrb.model.photo.PhotoFundVo;
import com.hanhai.zrb.model.photo.PhotoVo;
import com.hanhai.zrb.model.project.CityInfo;
import com.hanhai.zrb.model.project.Industry;
import com.hanhai.zrb.model.project.Project;
import com.hanhai.zrb.model.resourcematch.ResourceMatchContent;
import com.hanhai.zrb.model.resourcematch.ResourceMatchLevelEnum;
import com.hanhai.zrb.model.resourcematch.ResourceMatchResult;
import com.hanhai.zrb.model.resourcematch.ResourceMatchTypeEnum;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.UserInfo;
@Controller
@RequestMapping("fundBack")
public class FundController extends BaseController{
	@Resource
	private FundService fundService;
	
	@Resource
	private UserService userService;

	@Resource
	private FundFacade fundFacade;
	@Resource
	private CityInfoService cityInfoService;
	
	@Resource
	private IndustryService industryService;
	@Resource
	private ProjectFundSequenceService projectFundSequenceService;
	
	@Resource
	private BackUserService backUserService;
	@Resource
	private UserRoleService userRoleService;
	
	@Resource
	private IntentionService intentionService;
	
	@Resource
	private ProjectService projectService;
	
	@Autowired
	private ResourceMatchService resourceMatchService;
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response) {
		String page = request.getParameter("statusIds");
		if(StringUtils.isNotBlank(page)){
			return "fund/queryAppovList";
		}
		return "fund/queryList";
	}
	
	@RequestMapping("/my")
	public String my(Model model) {
		Integer my = 1;
		model.addAttribute("my", my);
		return "fund/queryList";
	}
		
	//投资方式单选
	@RequestMapping("/queryList")
	public void list(FundSearchDto dto,String statusIds,Integer page,Integer rows,Integer my,HttpServletResponse response) throws IOException{

		Map<String, Object> map = Maps.newHashMap();
		//List<UserInfo> list = new ArrayList<UserInfo>();		

		//判断关键字是否有值，如果有先根据用户真实姓名查询idlist然后再写入uidList进行查询
		if(null!=dto && StringUtils.isNotBlank(dto.getKeyword())){
			User users = userService.findByUname(dto.getKeyword());
			if(null!=users){
				dto.setUserId(users.getUid());
//				dto.setOwner(users.getUid());
			}
		}

		if(StringUtils.isNotBlank(statusIds)){
			List<Integer> statusList =new ArrayList<Integer>();
			String[] statusStr = statusIds.split(",");
			for (int i = 0; i < statusStr.length; i++) {
				if(StringUtils.isNumeric(statusStr[i])){
					statusList.add(Integer.valueOf(statusStr[i]));
				}
			}
			dto.setStatusList(statusList);
		}else{
			if(my != null){
				BackendUser userback = BackendLoginUtil.getCurrentUser();
				dto.setOperatorId(userback.getId());
			}
		}
	
		Map<String, Map<String, Object>> backUserMap = backUserService.getBackUserMap();
		PageInfo pageInfo =fundService.queryFundByFSearchDto(dto,backUserMap, page, rows);
		List<FundSearchVo> listVo =pageInfo.getList() ;
		//listVo = buildData(listVo);
		map.put("rows", listVo);
		map.put("total", pageInfo.getTotal());
		response.getWriter().write(JSONObject.toJSONString(map));
	}
	
	

	
	@RequestMapping("/updateStatus")
	@ResponseBody
	public String updateStatus(String ids ,String status){
		boolean ret = true ;
		Map<String, Object> map = Maps.newHashMap();
		BackendUser user = BackendLoginUtil.getCurrentUser();
	   	if(StringUtils.isNumeric(ids) && StringUtils.isNotBlank(status)){
              ret = fundService.updateStatus(Long.valueOf(ids), status,user.getId());
			
	   	}else{
	   		ret = false;
	   	}
		if(ret){
			map.put("success", true);
			map.put("infoMsg", "修改信息状态成功");
		}else{
			map.put("success", false);
			map.put("errorMsg", "修改信息状态失败,请稍后再试");
		}   	
		return JSON.toJSONString(map);
	}
	
	//更改会员状态
	@RequestMapping("/deleteFund")
	@ResponseBody
	public String deleteFund(String ids){
		boolean ret = true ;
		Map<String, Object> map = Maps.newHashMap();
		BackendUser user = BackendLoginUtil.getCurrentUser();
	   	if(StringUtils.isNotBlank(ids) ){
	   		List<Long> idList = new ArrayList();
			String[] str = ids.split(",");
			for (int i = 0; i < str.length; i++) {
				if(StringUtils.isNumeric(str[i])){
					idList.add(Long.valueOf(str[i]));
				}
			}
	   		ret = fundService.deleteFund(idList);
	   	}else{
	   		ret = false;
	   	}
		if(ret){
			map.put("success", true);
			map.put("infoMsg", "删除信息成功");
		}else{
			map.put("success", false);
			map.put("errorMsg", "删除信息失败,请稍后再试");
		}   	
		return JSON.toJSONString(map);
	}
	
	
	//修改
	@RequestMapping("/edit")
	@ResponseBody
	public String edit(Fund fund ,String userPhone,String addOrUpdate,String state,String intentionId,String titlesVal,HttpServletRequest request, HttpServletResponse response){
		boolean ret = true ;
		fund.setTitlesVal(titlesVal);
		if(StringUtils.isNumeric(intentionId)){
			fund.setIntention(Long.valueOf(intentionId));
		}
		BackendUser user = BackendLoginUtil.getCurrentUser();
		fund.setOperatorId(user.getId());
		fund.setOperatorTime(new Date());
		String destination = fund.getDestination();
		if(StringUtils.isNotBlank(destination)){
			fund.setDestination(destination.replaceAll(",", "#"));
		}
		String industry = fund.getIndustryId();
		if(StringUtils.isNotBlank(industry)){
			fund.setIndustryId(industry.replaceAll(",", "#"));
		}
		
		Map<String, Object> map = Maps.newHashMap();
		if(StringUtils.isNumeric(userPhone)){
			User  users = userService.findByPhone(userPhone);
			if(null!=users){
				fund.setUserId(users.getUid());
//				fund.setOwner(users.getUid());
			}
		}
		
		if(null!=fund.getId()){
			if(!"203".equals(state)){
				fund.setState(202);	
			}else{
				Fund temp = new Fund();
				temp.setId(fund.getId());
				temp.setDescrition(fund.getDescrition());
				temp.setRequirement(fund.getRequirement());
				temp.setIntention(fund.getIntention());
				fund = temp;
			}
			
			fund.setUpdateTime(new Date());
			ret = fundService.updateByPrimaryKeySelective(fund);

			
		}else{
			fund.setUpdateTime(new Date());
			fund.setInsertTime(new Date());
			fund.setState(202);
			String num = projectFundSequenceService.getNextFundSequence();
			fund.setFundNo(num);
			ret = fundService.insert(fund);
		}
		

		if(ret){
			map.put("success", true);
			map.put("msg", "资金管理编辑成功");
		}else{
			map.put("success", false);
			map.put("msg", "资金管理编辑失败");
		}   	
	   	return JSON.toJSONString(map);
	}
	
	
	
	@RequestMapping("/findAllIndustry")
	@ResponseBody
	public String findAllIndustry(HttpServletResponse response) {
		List<Industry> cityList = industryService.selectSquAll();
		List<Map<String, Object>> list = Lists.newArrayList();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", 0);
		map.put("text", "");
		for (Industry industry : cityList) {
			map = Maps.newHashMap();
			
			map.put("id", industry.getId());
			map.put("text", industry.getIndustryName().replaceAll("/", " "));
			list.add(map);
		}
		return JSON.toJSONString(list);
	}
	
	@RequestMapping(value="/detail")
	public String detail(Long id,Model model){
		AppFundDetailVo detail = fundFacade.getAppFundDetail(id);
		model.addAttribute("detail", detail);
		logger.info("user query fund detail successed");
		return "fund/fundsDetail";
	}

	
	
	//校验电话号码
	@RequestMapping("/checkPhone")
	@ResponseBody
	public String checkPhone(String userPhone){
		boolean ret = true ;
		Map<String, Object> map = Maps.newHashMap();
	   	User user = userService.findByPhone(userPhone);
		if(null!=user && !"".equals(user)){
			map.put("success", true);
			map.put("infoMsg", "");
		}else{
			map.put("success", false);
			map.put("errorMsg", "填写会员必须是注册会员");
		}  	
		return JSON.toJSONString(map);
	}
	//校验项目ID
	@RequestMapping("/checkFundNo")
	@ResponseBody
	public boolean checkFundNo(String fundNo,Long id){
		Map<String, Object> map = Maps.newHashMap();
		if(StringUtils.isNotBlank(fundNo)){
			List<Long> list =new ArrayList<Long>();
			if(null!=id && !"".equals(id)){
				list.add(id);
			}else{
				list =null;
			}
			List<Fund> fund = fundService.queryFundByFundNo(fundNo,list);
			if(null!=fund && !"".equals(fund)&& fund.size()>0){
	              return false;

			}else{
				return true;
			} 
		}else{
			return true;
		}
 	

	}
	
	@InitBinder
	@Override
	protected void initBinder(WebDataBinder binder) throws ServletException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);

		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(dateFormat, true));

		CustomCollectionEditor collectionEditor = new CustomCollectionEditor(List.class, true);

		binder.registerCustomEditor(List.class, collectionEditor);
	}
	
	@PermissionNeed("fundBack")
	@RequestMapping("managePhoto")
	public String managePhoto(HttpServletResponse response, Model model,
			@RequestParam Long id) {
		PhotoFundVo photoVo = fundService.viewPhoto(id);
		model.addAttribute("photoVo", photoVo);
		return "fund/fundPhoto";
	}
	
	@RequestMapping("viewPhoto")
	public String viewPhoto(HttpServletResponse response, Model model,
			@RequestParam Long id) {
		PhotoFundVo photoVo = fundService.viewPhoto(id);
		/*
		 * JSONObject jsonObject = new JSONObject(); jsonObject.put("photoVo",
		 * photoVo); super.returnJsonObject(response, jsonObject);
		 */
		model.addAttribute("photoVo", photoVo);
		return "fund/viewPhoto";
	}
	
	// 如果没有1个图是主图，默认第1个为主图
		@PermissionNeed("fundBack")
		@RequestMapping("savePhoto")
		public void savePhoto(HttpServletResponse response, @RequestParam Long id,
				String photos) {
			List<Photo> list = JSONArray.parseArray(photos, Photo.class);
			projectService.savePhoto(id, list, 2);
			super.jsonSucceed(response);
		}
		
		@RequestMapping("/showMarryProject")
		public String showMarryProject(String id,Integer type,HttpServletRequest request,HttpServletResponse response) {
			Long ids = null;
			if( StringUtils.isNotBlank(id)){
				ids = Long.valueOf(id);
				ResourceMatchResult recommends = new ResourceMatchResult();
				List<Project> queryByIdList = new ArrayList<Project>();
				if(type!=null && type.equals(IntentionTypeEnum.fund.getCode())){
					recommends = resourceMatchService.recommend(ResourceMatchTypeEnum.INTENTION_FUND.getCode(), ids );
				}else{
					recommends = resourceMatchService.recommend(ResourceMatchTypeEnum.FUND.getCode(), ids );
				}
				queryByIdList = getListvo(recommends);
				request.setAttribute("id", id);
				if( type == null){
					type = 103;
				}
				request.setAttribute("type", type);
				request.setAttribute("queryByIdsList", queryByIdList);
			}
			return "fund/showMarryProject";
		}

		private List<Project> getListvo(ResourceMatchResult recommends) {
			List<ResourceMatchContent> recommend = recommends.getResourceMatchContentList();
			List<Long> list = new ArrayList<Long>() ;
			for (int i = 0; i < recommend.size(); i++) {
				list.add(recommend.get(i).getBizid());
			}
			List<Project> queryByIdList = projectService.queryByIdsList(list);
			return queryByIdList;
		}
		
		@RequestMapping("/queryMarryProjectList")
		@ResponseBody
		public String queryMarryProjectList(Long id ,Integer type ,Integer page,Integer rows ,Integer level) {
			Map<String, Object> map = Maps.newHashMap();
			ResourceMatchResult matchPage = new ResourceMatchResult();
			if(type!=null && type.equals(IntentionTypeEnum.fund.getCode())){
				matchPage = getResourceMatchResult(id, ResourceMatchTypeEnum.INTENTION_FUND.getCode(), page, rows, level, matchPage);
			}else{
				matchPage = getResourceMatchResult(id, ResourceMatchTypeEnum.FUND.getCode(), page, rows, level, matchPage);
			}
			Page<ResourceMatchContent> resourceMatchContentPage = matchPage.getResourceMatchContentPage();
			List<Long> list = new ArrayList<Long>();
			List<Project> queryByIdList = new ArrayList<Project>();
			if( null!=resourceMatchContentPage && !resourceMatchContentPage.isEmpty()){
				for (ResourceMatchContent resourceMatchContent : resourceMatchContentPage) {
					list.add(resourceMatchContent.getBizid());
				}
//				List<FundSearchVo> findFundSearchVo = fundService.findFundSearchVo(list);
				queryByIdList = projectService.queryByIdsList(list);
				
			}
			if(matchPage != null){
		    	map.put("rows", queryByIdList);
		    	map.put("total", resourceMatchContentPage.getTotal());
		    }else{
		    	map.put("rows", Lists.newArrayList());
		    	map.put("total", 0);
		    }
			return JSON.toJSONString(map);
		}

		private ResourceMatchResult getResourceMatchResult(Long id, Integer code, 
				Integer page, Integer rows, Integer level,
				ResourceMatchResult matchPage) {
			if( null == level || ResourceMatchLevelEnum.ALL.getCode().equals(level)){
				matchPage = resourceMatchService.matchPage(
						code, id, page, rows,
						ResourceMatchLevelEnum.ALL);
			}else if( ResourceMatchLevelEnum.FIRST.getCode().equals(level)){
				matchPage = resourceMatchService.matchPage(
						code, id, page, rows,
						ResourceMatchLevelEnum.FIRST);
			}else if( ResourceMatchLevelEnum.SECOND.getCode().equals(level)){
				matchPage = resourceMatchService.matchPage(
						code, id, page, rows,
						ResourceMatchLevelEnum.SECOND);
			}else if( ResourceMatchLevelEnum.THIRD.getCode().equals(level)){
				matchPage = resourceMatchService.matchPage(
						code, id, page, rows,
						ResourceMatchLevelEnum.THIRD);
			}
			return matchPage;
		}
}
